"""
系统配置模块
基于Pydantic Settings的配置管理
"""
from typing import Optional, List
from pydantic_settings import BaseSettings
from pydantic import Field
from pathlib import Path
import os


class Settings(BaseSettings):
    """应用配置类"""
    
    # 基础配置
    app_name: str = Field(default="大模型信访分析系统", env="APP_NAME")
    app_version: str = Field(default="0.1.0", env="APP_VERSION")
    debug: bool = Field(default=False, env="DEBUG")
    
    # 服务器配置
    host: str = Field(default="0.0.0.0", env="HOST")
    port: int = Field(default=8000, env="PORT")
    
    # 数据库配置
    database_url: str = Field(
        default="sqlite:///./data/petition.db", 
        env="DATABASE_URL"
    )

    # 在Settings类中的HTTPS配置后添加
    # 天地图API配置
    tianditu_api_key: str = Field(
        default="347a929eeda90006869fea9391429f7f",
        env="TIANDITU_API_KEY"
    )
    local_data: str = Field(default="local_data", env="LOCAL_EXCEL")

        
    # JWT配置
    secret_key: str = Field(
        default="your-secret-key-change-in-production", 
        env="SECRET_KEY"
    )
    algorithm: str = Field(default="HS256", env="ALGORITHM")
    access_token_expire_minutes: int = Field(default=30, env="ACCESS_TOKEN_EXPIRE_MINUTES")
    
    # 文件上传配置
    upload_dir: str = Field(default="./upload", env="UPLOAD_DIR")
    max_file_size: int = Field(default=10 * 1024 * 1024, env="MAX_FILE_SIZE")  # 10MB
    allowed_extensions: List[str] = Field(
        default=[".xlsx", ".xls", ".csv"], 
        env="ALLOWED_EXTENSIONS"
    )
    
    # 日志配置
    log_level: str = Field(default="INFO", env="LOG_LEVEL")
    log_dir: str = Field(default="./logs", env="LOG_DIR")
    
    # AI服务配置
    ai_service_timeout: int = Field(default=30, env="AI_SERVICE_TIMEOUT")
    ai_service_max_retries: int = Field(default=3, env="AI_SERVICE_MAX_RETRIES")
    
    # 大模型API配置
    llm_provider: str = Field(default="openai", env="LLM_PROVIDER")  # openai, azure, anthropic, qwen, zhipu
    llm_api_key: str = Field(default="", env="LLM_API_KEY")
    llm_api_base: str = Field(default="https://api.openai.com/v1", env="LLM_API_BASE")
    llm_model: str = Field(default="gpt-3.5-turbo", env="LLM_MODEL")
    llm_max_tokens: int = Field(default=2000, env="LLM_MAX_TOKENS")
    llm_temperature: float = Field(default=0.7, env="LLM_TEMPERATURE")
    llm_timeout: int = Field(default=60, env="LLM_TIMEOUT")
    
    # Azure OpenAI配置
    azure_openai_api_version: str = Field(default="2023-12-01-preview", env="AZURE_OPENAI_API_VERSION")
    azure_openai_deployment_name: str = Field(default="", env="AZURE_OPENAI_DEPLOYMENT_NAME")
    
    # 通义千问配置
    qwen_api_key: str = Field(default="", env="QWEN_API_KEY")
    qwen_model: str = Field(default="qwen-turbo", env="QWEN_MODEL")
        # 智谱AI配置
    zhipu_api_key: str = Field(default="86db927d25ea4c58b660362946c389ed.6Bs8tbpH4syLQsqe", env="ZHIPU_API_KEY")
    zhipu_model: str = Field(default="glm-4-flash", env="ZHIPU_MODEL")
        # 天地图API配置
    tianditu_api_key: str = Field(default="", env="TIANDITU_API_KEY")
    # 任务队列配置（已移除Redis依赖）
    celery_broker_url: str = Field(
        default="memory://", 
        env="CELERY_BROKER_URL"
    )
    celery_result_backend: str = Field(
        default="cache://", 
        env="CELERY_RESULT_BACKEND"
    )
    
    # 邮件配置
    smtp_server: str = Field(default="smtp.gmail.com", env="SMTP_SERVER")
    smtp_port: int = Field(default=587, env="SMTP_PORT")
    smtp_username: str = Field(default="", env="SMTP_USERNAME")
    smtp_password: str = Field(default="", env="SMTP_PASSWORD")

    # HTTPS配置
    ssl_certfile: Optional[str] = "certs/server.crt"
    ssl_keyfile: Optional[str] = "certs/server.key"
    force_https: bool = True
    auto_generate_cert: bool = True
    cert_check_interval: int = 3600  # 1小时检查一次
    cert_renew_before_days: int = 30  # 30天前续期


    # 安全配置
    cors_origins: List[str] = Field(
        default=["http://localhost:3000", "http://localhost:8080"], 
        env="CORS_ORIGINS"
    )
    
    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = False
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 确保必要的目录存在
        self._ensure_directories()
    
    def _ensure_directories(self):
        """确保必要的目录存在"""
        directories = [
            self.upload_dir,
            self.log_dir,
            "./results",
            "./logs/daily",
            "./logs/errors"
        ]
        
        for directory in directories:
            Path(directory).mkdir(parents=True, exist_ok=True)
    
    @property
    def database_url_sync(self) -> str:
        """同步数据库连接URL"""
        return self.database_url.replace("+aiosqlite", "")
    
    @property
    def is_production(self) -> bool:
        """是否为生产环境"""
        return not self.debug
    
    @property
    def jwt_secret_key(self) -> str:
        """JWT密钥"""
        return self.secret_key


# 创建全局配置实例
settings = Settings()


# 环境变量配置示例
def create_env_example():
    """创建环境变量示例文件"""
    env_example = """# 应用配置
APP_NAME=大模型信访分析系统
APP_VERSION=0.1.0
DEBUG=False

# 服务器配置
HOST=0.0.0.0
PORT=8000

# 数据库配置
DATABASE_URL=sqlite:///./petition.db
# PostgreSQL示例: DATABASE_URL=postgresql://user:password@localhost/petition_db

# JWT配置
SECRET_KEY=your-secret-key-change-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# 文件上传配置
UPLOAD_DIR=./upload
MAX_FILE_SIZE=10485760
ALLOWED_EXTENSIONS=.xlsx,.xls,.csv

# 日志配置
LOG_LEVEL=INFO
LOG_DIR=./logs

# AI服务配置
AI_SERVICE_TIMEOUT=30
AI_SERVICE_MAX_RETRIES=3

# 大模型API配置
LLM_PROVIDER=openai
LLM_API_KEY=your-openai-api-key
LLM_API_BASE=https://api.openai.com/v1
LLM_MODEL=gpt-3.5-turbo
LLM_MAX_TOKENS=2000
LLM_TEMPERATURE=0.7
LLM_TIMEOUT=60

# Azure OpenAI配置
AZURE_OPENAI_API_VERSION=2023-12-01-preview
AZURE_OPENAI_DEPLOYMENT_NAME=

# 通义千问配置
QWEN_API_KEY=your-qwen-api-key
QWEN_MODEL=qwen-turbo

# 智谱AI配置
ZHIPU_API_KEY=86db927d25ea4c58b660362946c389ed.6Bs8tbpH4syLQsqe
ZHIPU_MODEL=glm-4-flash

# 任务队列配置（已移除Redis依赖）
CELERY_BROKER_URL=memory://
CELERY_RESULT_BACKEND=cache://

# 邮件配置
SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your-email@gmail.com
SMTP_PASSWORD=your-app-password

# 安全配置
CORS_ORIGINS=http://localhost:3000,http://localhost:8080

# 天地图API配置
TIANDITU_API_KEY=347a929eeda90006869fea9391429f7f
"""
    
    # env_path = Path(".env.example")
    env_path = ".env.example"
    # if not env_path.exists():
    if os.path.isfile(env_path):
        with open(env_path, "w", encoding="utf-8") as f:
            f.write(env_example)


# 初始化环境变量示例
create_env_example()


def get_settings():
    return Settings()